<template>
  <view class="container padding-bottom-80">
    <view style="margin-top: 120rpx;"></view>
    <!-- 使用通用导航栏组件 -->
    <nav-bar :title="storeId ? '编辑店铺' : '新增店铺'" />
    
    <uni-forms ref="form" :model="formData" :rules="rules">
      <uni-forms-item label="店铺名称" name="name">
        <uni-easyinput v-model="formData.name" placeholder="请输入店铺名称" />
      </uni-forms-item>
      <uni-forms-item label="店铺图片" name="image_url">
        <uni-file-picker v-model="formData.image_url" file-mediatype="image" limit="1" />
      </uni-forms-item>
      <uni-forms-item label="店铺地址" name="address">
        <uni-easyinput v-model="formData.address" placeholder="请输入店铺地址" />
      </uni-forms-item>
      
      <uni-forms-item label="联系电话" name="phone">
        <uni-easyinput v-model="formData.phone" placeholder="请输入联系电话" />
      </uni-forms-item>
      
      <uni-forms-item label="店铺描述" name="description">
        <uni-easyinput type="textarea" v-model="formData.description" placeholder="请输入店铺描述" />
      </uni-forms-item>
      
      <uni-forms-item label="营业时间" name="open_time">
        <view class="time-picker">
          <uni-easyinput 
            v-model="openHour" 
            placeholder="小时" 
            type="number" 
            :maxlength="2" 
            @input="updateTime('open')"
          />
          <text class="time-separator">:</text>
          <uni-easyinput 
            v-model="openMinute" 
            placeholder="分钟" 
            type="number" 
            :maxlength="2" 
            @input="updateTime('open')"
          />
		  </view>
		  <view class="time-separator">至</view>
		  <view class="time-picker">
          <uni-easyinput 
            v-model="closeHour" 
            placeholder="小时" 
            type="number" 
            :maxlength="2" 
            @input="updateTime('close')"
          />
          <text class="time-separator">:</text>
          <uni-easyinput 
            v-model="closeMinute" 
            placeholder="分钟" 
            type="number" 
            :maxlength="2" 
            @input="updateTime('close')"
          />
        </view>
      </uni-forms-item>
      
      <uni-forms-item label="店铺类型" name="store_type">
        <uni-data-checkbox 
          v-model="formData.store_type"
          :localdata="[
            { text: '理发店', value: '理发店' },
            { text: '美容店', value: '美容店' },
            { text: '按摩店', value: '按摩店' }
          ]"
        />
      </uni-forms-item>
    
      <button type="primary" @click="submitForm">保存修改</button>
    </uni-forms>
  </view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
import storeApi from '@/utils/store.js'

export default {
  components: {
    NavBar
  },
  data() {
    return {
      openHour: '',
      openMinute: '',
      closeHour: '',
      closeMinute: '',
      storeId: '',
      formData: {
        name: '',
        image_url: '',
        address: '',
        phone: '',
        description: '',
        open_time: '02:33',
        close_time: '',
        store_type: '理发店',
        hairdresser_commission_ratio: 0.0,
        washer_commission_ratio: 0.0,
        mentorship_split_ratio: 0.0
      },
      rules: {
        name: {
          rules: [{
            required: true,
            errorMessage: '请输入店铺名称'
          }]
        },
        address: {
          rules: [{
            required: true,
            errorMessage: '请输入店铺地址'
          }]
        },
        store_type: {
          rules: [{
            required: true,
            errorMessage: '请选择店铺类型'
          }]
        },
        phone: {
          rules: [{
            required: true,
            errorMessage: '请输入联系电话'
          }, {
            pattern: '^1[3-9]\\d{9}$',
            errorMessage: '请输入正确的手机号码'
          }]
        }
      },
      timeData: (() => {
        const hours = []
        for (let h = 0; h < 24; h++) {
          const hourStr = h < 10 ? `0${h}` : `${h}`
          const hour = {
            text: `${hourStr}时`,
            value: hourStr,
            level: 0,
            children: []
          }
          for (let m = 0; m < 60; m++) {
            const minuteStr = m < 10 ? `0${m}` : `${m}`
            hour.children.push({
              text: `${minuteStr}分`,
              value: minuteStr,
              level: 1
            })
          }
          hours.push(hour)
        }
        return hours
      })()
    }
  },
  onLoad(options) {
    this.storeId = options.id
    if(this.storeId) {
      this.getStoreDetail()
    }
  },
  methods: {
    back() {
      uni.navigateBack()
    },
    async getStoreDetail() {
      try {
        const res = await storeApi.getStoreById(this.storeId)
        if(res.data.open_time) {
          const [openHour, openMinute] = res.data.open_time.split(':');
          this.openHour = openHour || '';
          this.openMinute = openMinute || '';
          this.formData.open_time = res.data.open_time;
        }
        if(res.data.close_time) {
          const [closeHour, closeMinute] = res.data.close_time.split(':');
          this.closeHour = closeHour || '';
          this.closeMinute = closeMinute || '';
          this.formData.close_time = res.data.close_time;
        }
        this.formData = {
          name: res.data.name,
          address: res.data.address,
          phone: res.data.phone,
          description: res.data.description,
          open_time: res.data.open_time,
          close_time: res.data.close_time,
          store_type: res.data.store_type,
          image_url: res.data.image_url,
          hairdresser_commission_ratio: res.data.hairdresser_commission_ratio,
          washer_commission_ratio: res.data.washer_commission_ratio,
          mentorship_split_ratio: res.data.mentorship_split_ratio
        }
      } catch (error) {
        uni.showToast({
          title: '获取店铺信息失败',
          icon: 'none'
        })
      }
    },
    async submitForm() {
      try {
        const validateTime = (time, field) => {
          if (!time) return true;
          const [hour, minute] = time.split(':');
          const hourNum = parseInt(hour);
          const minuteNum = parseInt(minute);
          
          if (isNaN(hourNum) || hourNum < 0 || hourNum > 23) {
            throw new Error(`${field}小时必须在0-23之间`);
          }
          if (isNaN(minuteNum) || minuteNum < 0 || minuteNum > 59) {
            throw new Error(`${field}分钟必须在0-59之间`);
          }
          return true;
        };

        validateTime(this.formData.open_time, '开门时间');
        validateTime(this.formData.close_time, '关门时间');
        await this.$refs.form.validate()
        if(this.storeId) {
          await storeApi.updateStore(this.storeId, this.formData)
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          })
          uni.$emit('refreshStoreList')
        } else {
          const res = await storeApi.createStore(this.formData)
          this.storeId = res.data.store_id
          uni.showToast({
            title: '新增成功',
            icon: 'success'
          })
          uni.$emit('refreshStoreList')
        }
      } catch (error) {
        if (error.message) {
          uni.showToast({
            title: error.message,
            icon: 'none'
          })
        }
      }
    },
    updateTime(type) {
      if (type === 'open') {
        this.formData.open_time = `${this.openHour}:${this.openMinute}`;
      } else {
        this.formData.close_time = `${this.closeHour}:${this.closeMinute}`;
      }
    },
  }
}
</script>

<style>
.container {
  padding: 0 30rpx;
  background-color: #f5f5f5;
}

uni-forms {
  margin: 0 -30rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;
}
.time-picker {
  display: flex;
  align-items: center;
}
.time-separator {
  margin: 0 10rpx;
}
</style>